import EmptyTip from '@/components/EmptyTip';
import { WrapPageLoadLoading } from '@/components/PageLoadLoading';
import StandProductList from '@/components/product/StandProductList';
import StandProductSort, {
  SortFilter,
  SortFilterList2,
} from '@/components/product/StandProductSort';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import { ScrollView, View } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import './index.scss';

// 1为按销量排序  2为按价格 低到高   3 价格高到低  不传默认为按时间排
function transformSort(sort) {
  switch (sort) {
    case SortFilter.newProduct:
      return undefined;
    case SortFilter.sales:
      return 1;
    case SortFilter.up:
      return 2;
    case SortFilter.down:
      return 3;
    default:
      return undefined;
  }
}

const IndustryHeader = ({ list, activeId, changeActiveId }) => {
  const [scrollLeft, setScrollLeft] = useState(0);
  const [needDelay, setNeedDelay] = useState(false);

  const scrollToEle = (index) => {
    Taro.createSelectorQuery()
      .select('.industry-header-list')
      .fields({ scrollOffset: true })
      .select(`.industry-header-list .industry-header-${index}`)
      .fields({ rect: true })
      .exec((res) => {
        if (res[1] == null) {
          setNeedDelay(true);
          return;
        }
        const [{ scrollLeft: sf }, { left }] = res;
        let am = sf + left - utils.getSizeByScale(200);
        setScrollLeft(am > 0 ? am : 0);
      });
  };

  useEffect(() => {
    activeId >= 0 && scrollToEle(activeId);
  }, [activeId]);

  useEffect(() => {
    if (needDelay) {
      setTimeout(() => scrollToEle(activeId), 100);
      setNeedDelay(false);
    }
  }, [needDelay]);

  return (
    <ScrollView
      scrollX
      enableFlex
      scrollLeft={scrollLeft}
      scrollWithAnimation
      className="industry-header-list"
    >
      {list.map(({ title }, index) => {
        return (
          <View
            key={index}
            className={classNames(`industry-header industry-header-${index}`, {
              'active customePageStyle': activeId === index,
            })}
            onClick={() => {
              changeActiveId(index);
            }}
          >
            <View className="industry-text">{title}</View>
            <View
              className={classNames('industry-active', {
                customePageBackgroundStyle: activeId === index,
              })}
            ></View>
          </View>
        );
      })}
    </ScrollView>
  );
};

const pageSize = 20;

const ShopIndustry = ({
  dispatch,
  industry = [],
  recProductList = [],
  recProductFinished = false,
}) => {
  const [currentTab, setCurrentTab] = useState(-1);
  const [sort, setSort] = useState(SortFilter.newProduct);
  const [scrollTop, setScrollTop] = useState(0);

  const router = useRouter();
  const { params = {} } = router;

  const handleTabChanged = (index) => {
    if (index === currentTab) {
      return;
    }
    setCurrentTab(index);
  };

  const getRecommendProduct = (theIndustry) => {
    let theParams = { pageSize };
    const { id } = theIndustry;
    if (id) {
      theParams.industryId = parseInt(id);
    } else {
      theParams.industryId = parseInt(params.firstIndustryId);
    }

    theParams.sort = transformSort(sort);
    dispatch({
      type: 'productList/getShopIndustryProductList',
      payload: { ...theParams },
    });
  };

  const getIndustry = () => {
    dispatch({
      type: 'productList/getSecondIndustry',
      payload: { id: parseInt(params.firstIndustryId) },
    });
  };

  useDidShow(() => {
    if (params.name) {
      Taro.setNavigationBarTitle({
        title: decodeURIComponent(params.name),
      });
    }
  });

  useEffect(() => {
    getIndustry();
    return () => {
      dispatch({
        type: 'productList/setSecondIndustry',
        payload: { list: [] },
      });
      dispatch({
        type: 'productList/clearShopIndustryProductList',
        payload: {},
      });
    };
  }, []);

  useEffect(() => {
    if (industry.length > 0) {
      let index = 0;
      if (params.secondIndustryId) {
        for (let i = 0; i < industry.length; i++) {
          if (industry[i].id == params.secondIndustryId) {
            index = i;
            break;
          }
        }
      }
      setCurrentTab(index);
    }
  }, [industry]);

  useEffect(() => {
    setScrollTop(Math.random() / 1000);
    industry.length > 0 && getRecommendProduct(industry[currentTab]);
  }, [currentTab, sort]);

  const showNextRecommendProduct = debounce(() => {
    !recProductFinished && industry.length > 0 && getRecommendProduct(industry[currentTab]);
  }, 1200);

  return (
    <View className="ShopIndustryPage">
      <View className={classNames('industry-header-list-wrap-placeholder')}></View>
      <View id="industry-header-list-wrap" className="industry-header-list-wrap">
        <IndustryHeader list={industry} activeId={currentTab} changeActiveId={handleTabChanged} />
      </View>

      <View className="split-line"></View>

      <StandProductSort
        className="sort-area"
        {...{
          showBottom: false,
          customSortFilterList: SortFilterList2,
          value: sort,
          onChange: (v) => {
            setSort(v);
          },
        }}
      />

      <StandProductList
        className="industry-theme"
        {...{
          scrollTop,
          list: recProductList,
          isFinished: recProductFinished,
          onNext: showNextRecommendProduct,
          emptyTip: <EmptyTip type="noProduct" />,
          height: `calc(100vh - ${utils.getSizeByScale(196)}px)`,
          cartEle: null,
        }}
      />
    </View>
  );
};

export default connect(({ loading, productList }) => ({
  industry: productList.secondIndustry,
  recProductList: productList.shopIndustryProductList,
  recProductParams: productList.shopIndustryProductParams,
  recProductFinished: productList.shopIndustryProductListFinished,
  loading,
}))(WrapPageLoadLoading(ShopIndustry, { once: true }));
